package com.csc.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.csc.bean.RequestResetPassBean;
import com.csc.bean.SystemAccountBean;
import com.csc.domain.SystemAccount;
import com.csc.domain.TransactionHistory;
import com.csc.service.SystemAccountService;
import com.csc.service.SystemRequestService;
import com.csc.service.ValidatorService;

@Controller
@SessionAttributes("user")
public class SystemRequestController {
	@Autowired
	SystemRequestService requestService;

	@Autowired
	private SystemAccountService sysAccSer;

	@Autowired
	ValidatorService validateService;

	// Truong Le Bao - Mapping resetpassword page
	@RequestMapping(value = "/resetpassword", method = RequestMethod.GET)
	public String goResetPassword(HttpServletRequest request) {
		return "requestChangePassword";
	}

	// Truong Le Bao - List of Registered Users
	@RequestMapping(value = "/listuser")
	public String goNewUsers() {
		return "admin/listusers";
	}

	// Truong Le Bao - START Load Registered User JSON
	@RequestMapping(value = "/goRegisteredUsersJson", method = RequestMethod.GET)
	public @ResponseBody List<SystemAccountBean> goRegisteredUsersJson(@ModelAttribute("user") String username) {
		
		List<SystemAccount> list = sysAccSer.getRegisteredAccounts(username);
		
		return requestService.parseToUserProfiles(list);
	}

	// Truong Le Bao - END Load Registered User JSON

	// Truong Le Bao - JSON Request Registered detailed using JSON
	@RequestMapping(value = "/registeduserdetailjson/{username}", method = RequestMethod.POST)
	@ResponseBody
	public SystemAccount getRegisteredUserDetail(
			@PathVariable("username") String username) {

		SystemAccount acc = sysAccSer.getAccountByUsername(username);

		return acc;
	}

	// Truong Le Bao - End - JSON Request Registered detailed using JSON

	// Truong Le Bao - JSON Request Registered detailed using JSON
	@RequestMapping(value = "/advancedSearchRegisteredUsers/{fullname}/{username}/{idcard}/{phone}/{address}/{email}/{role}/{status}", method = RequestMethod.GET)
	@ResponseBody
	public List<SystemAccountBean> getAdvancedSearchRegisteredUser(
			@PathVariable("fullname") String fullname,
			@PathVariable("username") String username,
			@PathVariable("idcard") String idcard,
			@PathVariable("phone") String phone,
			@PathVariable("address") String address,
			@PathVariable("email") String email,
			@PathVariable("role") String role,
			@PathVariable("status") String status,
			@ModelAttribute("user") String loginID) {

		String[] variables = { fullname, username, idcard, phone, address,
				email, role, status };

		for (int i = 0; i < variables.length; i++) {
			if (variables[i].equals("null")) {
				variables[i] = "";
			}
		}

		List<SystemAccount> listResult = sysAccSer
				.searchAdvanceRegisteredAccounts(variables[0], variables[1],
						variables[2], variables[3], variables[4], variables[5],
						variables[6], variables[7], loginID);

		return requestService.parseToUserProfiles(listResult);
	}

	// Truong Le Bao - End - JSON Request Registered detailed using JSON

	// Truong Le Bao - JSON Request Registered detailed using JSON
	@RequestMapping(value = "/advancedSearchNewRequest/{fullname}/{username}/{role}/{from}/{to}", method = RequestMethod.GET)
	@ResponseBody
	public List<RequestResetPassBean> getAdvancedSearchNewRequest(
			@PathVariable("fullname") String fullname,
			@PathVariable("username") String username,
			@PathVariable("role") String role,
			@PathVariable("from") String from, @PathVariable("to") String to) {

		String[] variables = { fullname, username, role, from, to };

		for (int i = 0; i < variables.length; i++) {
			if (variables[i].equals("null")) {
				variables[i] = "";
			}
		}

		List<TransactionHistory> listTransaction = requestService
				.searchAdvanceNewRequests(variables[0], variables[1],
						variables[2], variables[3], variables[4]);

		return requestService.parseToRequestDetail(listTransaction);
	}

	// Truong Le Bao - End - JSON Request Registered detailed using JSON

/*	// Truong Le Bao - Show Current User Information in user/settings.jsp
	@RequestMapping(value = "/setting", method = RequestMethod.GET)
	public String goUserSetting(@ModelAttribute("user") String loginid,
			Model model) {
		SystemAccount acc = (SystemAccount) sysAccSer
				.getAccountByUsername(loginid);
		model.addAttribute("currentAccount", acc);
		return "user/settings";
	}*/

	// End - Truong Le Bao - Show Current User Information in user/settings.jsp

	// Truong Le Bao - List of New Request Reset Password
	@RequestMapping(value = "/newrequestresetpassword")
	public String goNewRequestsReset() {
		return "admin/newRequestReset";
	}

	// Truong Le Bao - START Load Request Reset Password User JSON
	@RequestMapping(value = "/goNewRequestResetPassJson", method = RequestMethod.GET)
	public @ResponseBody List<RequestResetPassBean> goNewRequestResetPassJson() {
		return requestService.getNewRequests();
	}

	// Truong Le Bao - END Load Request Reset Password User JSON

	// Truong Le Bao - JSON Transaction Reset Password Detail using JSON
	@RequestMapping(value = "/transactionDetailJson/{transactionID}", method = RequestMethod.POST)
	@ResponseBody
	public TransactionHistory getTransactionDetail(
			@PathVariable("transactionID") int transactionID) {
		return requestService.getTransactionByID(transactionID);
	}

	// Truong Le Bao - End - JSON Transaction Reset Password Detail using JSON

	// Truong Le Bao - Send request reset password
	@RequestMapping(value = "/requestresetpassword")
	public String sendRequestResetPassword(
			@RequestParam("txtUsername") String username,
			@RequestParam("txtReason") String reason, Model model) {
		
		String message = validateService.checkRequestResetPassword(username);

		if (!message.equals("")) {
			model.addAttribute("messageNoAccount", message);
		} else {
			boolean result = requestService.requestResetPassword(username,
					reason);

			if (result) {
				message = "Your request for resetting password has been sent successfully and will be soon processed. <br> Please check your email account for new password.";
			} else {
				message = "The server is under maintenance, please visit again few hours later....!";
			}
			model.addAttribute("messageResult", message);
		}

		return "requestChangePassword";
	}

	// Truong Le Bao - End - Send request reset password

	// Truong Le Bao - Process request reset password
	@RequestMapping(value = "/processresetpassword")
	public String processResetPassword(
			@RequestParam("txtTransactionID") String transactionID,
			@RequestParam("txtCurrentUsername") String currentUser,
			@RequestParam("txtRequestUsername") String requestUsername,
			@RequestParam("action") String action, Model model,
			HttpServletRequest request) {

		// Check kinds of process: save or reject
		int status = 0;

		if (action.equals("reset")) {
			status = 5;
		} else if (action.equals("reject")) {
			status = 6;
		}
		// End - Check kinds of process: save or reject

		// Process Update
		//String realPath = request.getSession().getServletContext()
		//		.getRealPath("resources/requests/");
		
		boolean result = requestService.processRequestResetPassword(
				transactionID, currentUser, requestUsername, status,
				"");

		if (result) {
			if (action.equals("reset")) {
				model.addAttribute("messageResult", requestUsername
						+ "'s password has been reset successfully");
			} else {
				model.addAttribute("messageResult", requestUsername
						+ "'s request has been rejected successfully");
			}
		} else {
			model.addAttribute("messageResult",
					"The server is under maintenance, please visit again few hours later....!");
		}
		// End - Process Update

		return "forward:/newrequestresetpassword.html";
	}

	// Truong Le Bao - End - Process request reset password

	// Truong Le Bao - JSON Validate New Profile using JSON
	@RequestMapping(value = "/validateNewProfile/{username}/{idcard}/{firstname}/{midname}/{lastname}/{phone1}/{phone2}/{address1}/{address2}/{email1}/{email2}", method = RequestMethod.POST)
	@ResponseBody
	public String[] validateNewProfile(
			@PathVariable("username") String username,
			@PathVariable("idcard") String idcard,
			@PathVariable("firstname") String firstname,
			@PathVariable("midname") String midname,
			@PathVariable("lastname") String lastname,
			@PathVariable("phone1") String phone1,
			@PathVariable("phone2") String phone2,
			@PathVariable("address1") String address1,
			@PathVariable("address2") String address2,
			@PathVariable("email1") String email1,
			@PathVariable("email2") String email2) {

		// Set null value
		String[] variables = { username, idcard, firstname, midname, lastname,
				phone1, phone2, address1, address2, email1, email2 };
		for (int i = 0; i < variables.length; i++) {
			if (variables[i].equals("null")) {
				variables[i] = "";
			}
		}
		// End Set null value

		// Set new properties for SystemAccountBean
		SystemAccountBean acc = new SystemAccountBean();
		acc.setAccountLoginId(variables[0]);
		acc.setAccountIDCardNumber(variables[1]);
		acc.setAccountFirstName(variables[2]);
		acc.setAccountLastName(variables[3]);
		acc.setAccountMidName(variables[4]);
		acc.setAccountPhone1(variables[5]);
		acc.setAccountPhone2(variables[6]);
		acc.setAccountAddress1(variables[7]);
		acc.setAccountAddress2(variables[8]);
		acc.setAccountEmail1(variables[9]);
		acc.setAccountEmail2(variables[10]);
		// End - set new properties for SystemAccountBean

		return validateService.checkAccountProperties(acc);
	}

	// Truong Le Bao - End - JSON Validate New Profile using JSON

	// Truong Le Bao - Process Update Profile
	@RequestMapping(value = "/processupdateprofile")
	public String processUpdateProfile(
			@RequestParam("txtCurrentUser") String currentUser,
			@RequestParam("txtRequestUsername") String requestUsername,
			@RequestParam("txtIdCardNumber") String idCardNumber,
			@RequestParam("txtFirstName") String firstName,
			@RequestParam("txtLastName") String lastName,
			@RequestParam("txtMidName") String midName,
			@RequestParam("txtPhone1") String phone1,
			@RequestParam("txtPhone2") String phone2,
			@RequestParam("txtEmail1") String email1,
			@RequestParam("txtEmail2") String email2,
			@RequestParam("txtAddress1") String address1,
			@RequestParam("txtAddress2") String address2, Model model) {

		// Set new properties for SystemAccountBean
		SystemAccountBean acc = new SystemAccountBean();
		acc.setAccountLoginId(requestUsername);
		acc.setAccountIDCardNumber(idCardNumber);
		acc.setAccountFirstName(firstName);
		acc.setAccountLastName(lastName);
		acc.setAccountMidName(midName);
		acc.setAccountPhone1(phone1);
		acc.setAccountPhone2(phone2);
		acc.setAccountEmail1(email1);
		acc.setAccountEmail2(email2);
		acc.setAccountAddress1(address1);
		acc.setAccountAddress2(address2);
		// End - set new properties for SystemAccountBean

		// Process Update
		boolean result = requestService.processRequestUpdateProfile(acc,
				currentUser);
		if (result) {
			model.addAttribute("messageResult", requestUsername
					+ "'s profile has been edited successfully");
		} else {
			model.addAttribute("messageError",
					"- The server is under maintenance, please visit again few hours later....!");
		}
		// End - Process Update

		return "forward:/listuser.html";
	}
	// Truong Le Bao - End - Process Update Profile
}